import { SmsChannelInfo } from 'admin/schema/CorporateSet';
import { querySmsChannelList, updateSmsChannel } from 'admin/servers/servers';
import { Form, message, Modal, Select } from 'antd';
import React, { useEffect, useState } from 'react';
import { verifyNull } from 'utils/tools';

type Props = {
  visible: boolean;
  currentDetail: SmsChannelInfo;
  successFn: Function;
  cancelFn: Function;
};

/**弹窗-设置 */
export const DetailModal: React.FC<Props> = ({ visible, currentDetail, successFn, cancelFn }) => {
  const [form] = Form.useForm();
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [smsChannelList, setSmsChannelList] = useState<any>([]);
  const { Option } = Select;

  useEffect(() => {
    if (visible) {
      fetchData();
    }
  }, [visible]);

  /**获取短信通道列表 */
  const fetchData = async () => {
    try {
      const { data = [] } = await querySmsChannelList();
      setSmsChannelList(data);
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  };

  /**
   * 表单提交
   * @param values
   */
  const onFinish = async ({ smsGatewayId }: SmsChannelInfo) => {
    const data = {
      smsGatewayId,
    };
    setConfirmLoading(true);
    try {
      await updateSmsChannel(data);
      message.success('设置成功');
      successFn();
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setConfirmLoading(false);
  };
  const handleOK = () => {
    form.submit();
  };
  const handleCancel = () => {
    form.resetFields();
    cancelFn();
  };
  const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 16 },
  };

  return (
    <Modal
      title="设置短信网关"
      visible={visible}
      confirmLoading={confirmLoading}
      onOk={handleOK}
      onCancel={handleCancel}
    >
      <Form
        form={form}
        {...layout}
        onFinish={onFinish}
        initialValues={{
          smsGatewayId: currentDetail.smsGatewayId,
        }}
      >
        <Form.Item name="smsGatewayId" label="短信网关" rules={verifyNull('请选择')}>
          <Select>
            {smsChannelList.length > 0 &&
              smsChannelList.map((item: any) => {
                return (
                  <Option key={item.smsGatewayId} value={item.smsGatewayId}>
                    {item.smsGatewayName}
                  </Option>
                );
              })}
          </Select>
        </Form.Item>
      </Form>
    </Modal>
  );
};
